<template>
  <div class="app-container">
    <!-- 统计卡片 -->
    <div class="stats-cards">
      <div class="stat-card income">
        <div class="stat-label">入账金额</div>
        <div class="stat-value">+¥ {{ todayIncome }}</div>
      </div>
      <div class="stat-card expense">
        <div class="stat-label">出账金额</div>
        <div class="stat-value">-¥ {{ todayExpense }}</div>
      </div>
    </div>

    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" class="search-form">
      <el-form-item label="账单类型" prop="billType">
        <el-select v-model="queryParams.billType" placeholder="请选择账单类型" clearable>
          <el-option label="全部" value=""></el-option>
          <el-option label="收入" value="1"></el-option>
          <el-option label="支出" value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="交易状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择交易状态" clearable>
          <el-option label="全部" value=""></el-option>
          <el-option label="成功" value="1"></el-option>
          <el-option label="失败" value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="日期" prop="dateRange">
        <el-date-picker
          v-model="queryParams.dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">搜索</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据表格 -->
    <el-table :data="tableData" style="width: 100%" v-loading="loading">
      <el-table-column label="账单类型" prop="billType" align="center">
        <template #default="scope">
          <span :class="scope.row.billType === '收入' ? 'income-text' : 'expense-text'">
            {{ scope.row.billType }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="金额(元)" prop="amount" align="center">
        <template #default="scope">
          <span :class="scope.row.billType === '收入' ? 'income-amount' : 'expense-amount'">
            {{ scope.row.amount }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="记录消息" prop="orderNo" align="center" show-overflow-tooltip></el-table-column>
      <el-table-column label="交易状态" prop="status" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.status === '成功' ? 'success' : 'danger'">
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="createTime" align="center" width="180"></el-table-column>
      <template #empty>
        <el-empty description="暂无账单记录" />
      </template>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      v-show="total > 0"
      :current-page="queryParams.pageNum"
      :page-size="queryParams.pageSize"
      :page-sizes="[10, 20, 50, 100]"
      :total="total"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script setup name="BillRecord">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getToken } from '@/utils/auth'
import {listShopDetail} from '@/api/order/merchantBillDetail.js'
import {listShop} from '@/api/order/shop.js'
import {listBusiness} from '@/api/order/business.js'
import {listShopwithdraw} from '@/api/order/shopwithdraw.js'

// 加载状态
const loading = ref(false)
// 总条数
const total = ref(0)
// 表格数据
const tableData = ref([])
// 统计数据
const todayIncome = ref(0)
const todayExpense = ref(0)
// 当前用户信息
const currentUserId = ref(null)
const currentShopId = ref(null)
const currentShopName = ref('')

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  billType: '',
  status: '',
  dateRange: []
})

// 查询表单引用
const queryRef = ref()

// 解析token获取用户ID
const getCurrentUserId = () => {
  try {
    const token = getToken()
    
    if (token) {
      // 如果token是JWT格式，解析payload部分
      if (token.includes('.')) {
        const parts = token.split('.')
        
        if (parts.length === 3) {
          const payload = JSON.parse(atob(parts[1]))
          return payload.userId || payload.user_id || payload.id || payload.sub
        }
      }
      // 如果不是JWT格式，尝试直接使用token作为用户标识
      return token
    }
  } catch (error) {
    console.error('解析token失败:', error)
  }
  return null
}

// 获取商家信息
const getBusinessInfo = async (userId) => {
  try {
    const params = { 
      userId: userId,
      user_id: userId,
      id: userId
    }
    
    const response = await listBusiness(params)
    
    if (response && response.code === 200 && response.data) {
      return Array.isArray(response.data) ? response.data[0] : response.data
    } else if (response && response.rows) {
      return Array.isArray(response.rows) ? response.rows[0] : response.rows
    }
  } catch (error) {
    console.error('获取商家信息失败:', error)
  }
  return null
}

// 获取店铺信息
const getShopInfo = async (shopId) => {
  try {
    // 获取所有店铺列表，然后筛选
    const response = await listShop({})
    
    if (response && response.code === 200 && response.rows) {
      // 从返回的数组中找到匹配的店铺
      const shops = response.rows
      
      // 根据shopId精确匹配
      const targetShop = shops.find(shop => 
        shop.shopId == shopId || 
        shop.shop_id == shopId || 
        shop.id == shopId
      )
      
      return targetShop
    } else if (response && response.data) {
      // 如果返回的是data字段
      const shops = Array.isArray(response.data) ? response.data : [response.data]
      
      const targetShop = shops.find(shop => 
        shop.shopId == shopId || 
        shop.shop_id == shopId || 
        shop.id == shopId
      )
      
      return targetShop
    }
  } catch (error) {
    console.error('获取店铺信息失败:', error)
  }
  return null
}

// 获取提现记录
const getWithdrawRecords = async (shopName) => {
  try {
    if (!shopName) {
      return []
    }
    
    // 获取所有提现记录，然后筛选
    const response = await listShopwithdraw({})
    
    if (response && response.code === 200 && response.rows) {
      const allRecords = response.rows
      
      // 筛选出指定店铺且状态为"到账成功"的记录
      const filteredRecords = allRecords.filter(record => {
        const matchShop = record.shopName === shopName
        const isSuccess = record.status === '到账成功'
        return matchShop && isSuccess
      })
      
      return filteredRecords
    } else if (response && response.data) {
      const allRecords = Array.isArray(response.data) ? response.data : [response.data]
      
      const filteredRecords = allRecords.filter(record => {
        const matchShop = record.shopName === shopName
        const isSuccess = record.status === '到账成功'
        return matchShop && isSuccess
      })
      
      return filteredRecords
    }
  } catch (error) {
    console.error('获取提现记录失败:', error)
  }
  return []
}

// 获取收支明细
const getBillDetails = async (shopId) => {
  try {
    if (!shopId) {
      return []
    }
    
    const params = { 
      tenantId: shopId,
      shopId: shopId,
      shop_id: shopId
    }
    
    const response = await listShopDetail(params)
    
    if (response && response.code === 200 && response.data) {
      return Array.isArray(response.data) ? response.data : response.data.records || []
    } else if (response && response.rows) {
      return Array.isArray(response.rows) ? response.rows : []
    }
  } catch (error) {
    console.error('获取收支明细失败:', error)
  }
  return []
}

// 处理账单数据
const processBillData = (withdrawRecords, billDetails) => {
  const allBills = []
  let totalIncomeAmount = 0
  let totalExpenseAmount = 0

  // 处理提现记录（出账）
  withdrawRecords.forEach(record => {
    // 根据表格数据，金额字段是 withdrawAmount
    const amount = parseFloat(record.withdrawAmount || record.actualAmount || 0)
    
    // 优先使用recordMsg字段，如果没有则显示提现金额信息
    let message = record.recordMsg || record.record_msg || record.remark || record.description
    if (!message) {
      message = `提现出账 ${amount.toFixed(2)} 元`
    }
    
    const bill = {
      billType: '支出',
      amount: amount.toFixed(2),
      orderNo: message,
      createTime: record.submitTime || record.processTime || record.createTime,
      status: '成功'
    }
    allBills.push(bill)

    // 统计总支出
    totalExpenseAmount += amount
    console.log(`提现记录: ${amount}, 累计支出: ${totalExpenseAmount}`)
  })

  // 处理收支明细
  billDetails.forEach((detail, index) => {
    let billType = ''
    const amount = parseFloat(detail.amount || 0)
    let message = ''

    // 根据bill_type字段判断收入还是支出
    const type = detail.bill_type || detail.billType || detail.type

    // 根据实际的bill_type值进行判断
    if (type === '下单' || type === 'order' || type === '收入' || type === 'income') {
      billType = '收入'
      totalIncomeAmount += amount
      console.log(`收入记录: ${amount}, 累计收入: ${totalIncomeAmount}`)
    } else if (type === '售后' || type === 'refund' || type === '支出' || type === 'expense') {
      billType = '支出'
      totalExpenseAmount += amount
      console.log(`支出记录: ${amount}, 累计支出: ${totalExpenseAmount}`)
    } else {
      // 根据金额正负判断
      if (amount > 0) {
        billType = '收入'
        totalIncomeAmount += amount
        console.log(`正数金额判断为收入: ${amount}, 累计收入: ${totalIncomeAmount}`)
      } else {
        billType = '支出'
        totalExpenseAmount += Math.abs(amount)
        console.log(`负数金额判断为支出: ${Math.abs(amount)}, 累计支出: ${totalExpenseAmount}`)
      }
    }

    // 优先使用record_msg字段作为记录消息
    message = detail.record_msg || detail.recordMsg || detail.remark || detail.message
    if (!message) {
      if (billType === '收入') {
        message = `入账 ${Math.abs(amount).toFixed(2)} 元`
      } else {
        message = `出账 ${Math.abs(amount).toFixed(2)} 元`
      }
    }

    const bill = {
      billType: billType,
      amount: Math.abs(amount).toFixed(2),
      orderNo: message,
      createTime: detail.create_time || detail.createTime,
      status: detail.status === 1 ? '成功' : '失败'
    }
    
    allBills.push(bill)
  })

  // 更新统计数据
  console.log(`最终统计 - 总收入: ${totalIncomeAmount}, 总支出: ${totalExpenseAmount}`)
  todayIncome.value = totalIncomeAmount.toFixed(2)
  todayExpense.value = totalExpenseAmount.toFixed(2)
  console.log(`设置显示值 - 收入: ${todayIncome.value}, 支出: ${todayExpense.value}`)

  // 重新根据最终的billType计算统计数据，确保准确性
  totalIncomeAmount = 0
  totalExpenseAmount = 0
  
  allBills.forEach(bill => {
    const amount = parseFloat(bill.amount)
    if (bill.billType === '收入') {
      totalIncomeAmount += amount
    } else if (bill.billType === '支出') {
      totalExpenseAmount += amount
    }
  })
  
  console.log(`重新计算后 - 总收入: ${totalIncomeAmount}, 总支出: ${totalExpenseAmount}`)
  todayIncome.value = totalIncomeAmount.toFixed(2)
  todayExpense.value = totalExpenseAmount.toFixed(2)

  return allBills.sort((a, b) => new Date(b.createTime) - new Date(a.createTime))
}

// 过滤数据
const filterData = (data) => {
  let filteredData = [...data]

  // 按账单类型过滤
  if (queryParams.billType) {
    const typeMap = { '1': '收入', '2': '支出' }
    filteredData = filteredData.filter(item => item.billType === typeMap[queryParams.billType])
  }

  // 按状态过滤
  if (queryParams.status) {
    const statusMap = { '1': '成功', '0': '失败' }
    filteredData = filteredData.filter(item => item.status === statusMap[queryParams.status])
  }

  // 按日期范围过滤
  if (queryParams.dateRange && queryParams.dateRange.length === 2) {
    const [startDate, endDate] = queryParams.dateRange
    filteredData = filteredData.filter(item => {
      const itemDate = item.createTime.split(' ')[0]
      return itemDate >= startDate && itemDate <= endDate
    })
  }

  return filteredData
}

// 查询
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置
const resetQuery = () => {
  queryRef.value.resetFields()
  handleQuery()
}

// 分页大小改变
const handleSizeChange = (newSize) => {
  queryParams.pageSize = newSize
  queryParams.pageNum = 1
  getList()
}

// 当前页改变
const handleCurrentChange = (newPage) => {
  queryParams.pageNum = newPage
  getList()
}

// 获取列表数据
const getList = async () => {
  if (!currentShopId.value) {
    console.warn('店铺ID不存在，无法获取数据')
    return
  }

  loading.value = true
  try {
    // 获取提现记录和收支明细
    const [withdrawRecords, billDetails] = await Promise.all([
      getWithdrawRecords(currentShopName.value),
      getBillDetails(currentShopId.value)
    ])

    // 处理数据
    const allBills = processBillData(withdrawRecords, billDetails)
    
    // 过滤数据
    const filteredData = filterData(allBills)
    
    // 分页处理
    total.value = filteredData.length
    const startIndex = (queryParams.pageNum - 1) * queryParams.pageSize
    const endIndex = startIndex + queryParams.pageSize
    tableData.value = filteredData.slice(startIndex, endIndex)

  } catch (error) {
    console.error('获取数据失败:', error)
    tableData.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 初始化数据
const initData = async () => {
  // 获取当前用户ID
  currentUserId.value = getCurrentUserId()
  
  if (!currentUserId.value) {
    ElMessage.error('无法获取当前用户信息，请重新登录')
    return
  }

  try {
    // 获取商家信息
    const businessInfo = await getBusinessInfo(currentUserId.value)
    
    // 尝试不同的字段名来获取shopId
    const shopId = businessInfo.shopId || businessInfo.shop_id || businessInfo.id
    
    if (!businessInfo || !shopId) {
      ElMessage.warning('未找到商家信息或店铺ID，请联系管理员')
      return
    }

    currentShopId.value = shopId

    // 获取店铺信息
    const shopInfo = await getShopInfo(currentShopId.value)
    
    if (shopInfo) {
      // 根据表格数据，字段名应该是 shop_name
      currentShopName.value = shopInfo.shop_name || shopInfo.shopName || shopInfo.name || shopInfo.storeName
    }
    
    if (!currentShopName.value) {
      ElMessage.warning('未能获取到店铺名称')
      return
    }

    // 获取账单数据
    await getList()
  } catch (error) {
    console.error('初始化数据失败:', error)
    ElMessage.error('数据加载失败，请刷新页面重试')
  }
}

// 页面加载时初始化数据
onMounted(() => {
  initData()
})

</script>

<style scoped>
.app-container {
  padding: 20px;
}

/* 统计卡片样式 */
.stats-cards {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  flex: 1;
  padding: 20px;
  border-radius: 8px;
  color: white;
  min-height: 80px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.stat-card.income {
  background: linear-gradient(135deg, #36d1dc 0%, #5b86e5 100%);
}

.stat-card.expense {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-label {
  font-size: 14px;
  opacity: 0.9;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
}

/* 搜索表单样式 */
.search-form {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

/* 表格文本颜色 */
.income-text {
  color: #67c23a;
  font-weight: bold;
}

.expense-text {
  color: #f56c6c;
  font-weight: bold;
}

.income-amount {
  color: #67c23a;
  font-weight: bold;
}

.expense-amount {
  color: #f56c6c;
  font-weight: bold;
}
</style>